package com.platform.auth.service;

import com.platform.common.core.constant.*;
import com.platform.common.core.domain.R;
import com.platform.common.core.domain.entity.PlatApp;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.enums.UserStatus;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.text.Convert;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.ip.IpUtils;
import com.platform.common.redis.service.RedisService;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.system.api.remote.api.RemoteSystemService;
import com.platform.usercenter.api.remote.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Date;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RemoteSystemService remoteSystemService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password, HttpServletRequest request) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
//        // 密码如果不在指定范围内 错误
//        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
//                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
//            throw new ServiceException("用户密码不在指定范围");
//        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();

        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);

        // 查询应用-接口操作列表
        R<Map<String, String>> result = remoteSystemService.getApp2ApiList(ServiceNameConstants.AUTH_SERVICE);
        if (result.getCode() != HttpStatus.SUCCESS) {
            throw new ServiceException(result.getMsg());
        }
        Map<String, String> app2apiList = result.getData();
        if (app2apiList == null) {
            throw new ServiceException("应用列表查询失败");
        }
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");

        // 判断 密码是否已经半年没有更改 ，
        if (userInfo.getModifyPwdTime() != null && (System.currentTimeMillis() - userInfo.getModifyPwdTime().getTime() < UserConstants.HALF_YEAR)) {

        } else {
            userInfo.setModifyPwdTime(null);
        }

        // 登入成功后常用Ip变更提醒
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();

            String publicIp = inetAddress.getHostAddress();
            //模拟
            user.setLoginIp(publicIp);
            String previousIp = user.getLoginIp();
            if (previousIp != null && !previousIp.equals(publicIp)) {
                userInfo.setIpCode(null);
            } else {
                userInfo.setIpCode(publicIp);
            }
            //登录设备ip
            remoteUserService.addIp(user, SecurityConstants.INNER);
        } catch (Exception e) {
            e.printStackTrace();
            StackTraceElement stackTraceElement= e.getStackTrace()[0];
            System.out.println("系统出错，错误信息:"+e.toString()+" at "+stackTraceElement.getClassName()+"."+stackTraceElement.getMethodName()+":"+stackTraceElement.getLineNumber());
        }
        return userInfo;
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setModifyPwdTime(new Date());
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
    }

    /**
     * 外部应用登录
     *
     * @param appKey    应用唯一标识
     * @param appSecret 应用秘钥
     */
    public PlatApp appLogin(String appKey, String appSecret) {
        R<PlatApp> result = remoteSystemService.getAppInfo(appKey, ServiceNameConstants.AUTH_SERVICE);
        if (result.getCode() != HttpStatus.SUCCESS) {
            throw new ServiceException(result.getMsg());
        }
        PlatApp platApp = result.getData();
        if (platApp == null) {
            throw new ServiceException("应用不存在");
        }
        passwordService.validate(platApp, appSecret);

        // 查询应用-接口操作列表
        R<Map<String, String>> resultMap = remoteSystemService.getApp2ApiList(ServiceNameConstants.AUTH_SERVICE);
        if (resultMap.getCode() != HttpStatus.SUCCESS) {
            throw new ServiceException(resultMap.getMsg());
        }
        Map<String, String> app2apiList = resultMap.getData();
        if (app2apiList == null) {
            throw new ServiceException("应用列表查询失败");
        }

        return platApp;
    }

    /**
     * 手机号登录
     */
    public LoginUser loginByphone(String phone, HttpServletRequest request){
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.infoByPhonenumber(phone, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + phone + " 不存在");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();

        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + phone + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + phone + " 已停用");
        }

        // 查询应用-接口操作列表
//        R<Map<String, String>> result = remoteSystemService.getApp2ApiList(ServiceNameConstants.AUTH_SERVICE);
//        if (result.getCode() != HttpStatus.SUCCESS) {
//            throw new ServiceException(result.getMsg());
//        }
//        Map<String, String> app2apiList = result.getData();
//        if (app2apiList == null) {
//            throw new ServiceException("应用列表查询失败");
//        }
//        recordLogService.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "登录成功");

        // 判断 密码是否已经半年没有更改 ，
        if (userInfo.getModifyPwdTime() != null && (System.currentTimeMillis() - userInfo.getModifyPwdTime().getTime() < UserConstants.HALF_YEAR)) {

        } else {
            userInfo.setModifyPwdTime(null);
        }

        // 登入成功后常用Ip变更提醒
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();

            String publicIp = inetAddress.getHostAddress();
            //模拟
            user.setLoginIp(publicIp);
            String previousIp = user.getLoginIp();
            if (previousIp != null && !previousIp.equals(publicIp)) {
                userInfo.setIpCode(null);
            } else {
                userInfo.setIpCode(publicIp);
            }
            //登录设备ip
            remoteUserService.addIp(user, SecurityConstants.INNER);
        } catch (Exception e) {
            e.printStackTrace();
            StackTraceElement stackTraceElement= e.getStackTrace()[0];
            System.out.println("系统出错，错误信息:"+e.toString()+" at "+stackTraceElement.getClassName()+"."+stackTraceElement.getMethodName()+":"+stackTraceElement.getLineNumber());
        }
        return userInfo;
    }
}
